﻿using System;
using System.Data;
using System.Reflection;

namespace Core.Core
{
    public class BaseConvert
    {
        /// <summary>
        /// 通过DataRow 填充实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ConvertToModel<T>(DataRow dr) where T : new()
        {
            T model = new T();
            foreach (PropertyInfo pInfo in model.GetType().GetProperties())
            {
                object val = getValueByColumnName(dr, pInfo.Name);
                if (val == null)
                {
                    val = getDefaultValue(pInfo.PropertyType);
                }
                pInfo.SetValue(model, val, null);
            }
            return model;
        }

        /// <summary>
        /// 切换默认值
        /// </summary>
        /// <param name="tp"></param>
        /// <returns></returns>
        private static object getDefaultValue(Type tp)
        {
            object v = null;
            switch (tp.ToString())
            {
                case "System.Boolean":
                    v = false;
                    break;
                case "System.Byte":
                    v = 0;
                    break;
                case "System.SByte":
                    v = 0;
                    break;
                case "System.Char":
                    v = "";
                    break;
                case "System.Decimal":
                    v = 0.0m;
                    break;
                case "System.Double":
                    v = 0d;
                    break;
                case "System.Single":
                    v = 0.0f;
                    break;
                case "System.Int32":
                    v = 0;
                    break;
                case "System.UInt32":
                    v = 0;
                    break;
                case "System.Int64":
                    v = 0;
                    break;
                case "System.UInt64":
                    v = 0;
                    break;
                case "System.Int16":
                    v = 0;
                    break;
                case "System.UInt16":
                    v = 0;
                    break;
                case "System.String":
                    v = "";
                    break;
                default:
                    break;
            }
            return v;
        }

        //返回DataRow 中对应的列的值。
        private static object getValueByColumnName(DataRow dr, string columnName)
        {
            if (dr != null)
            {
                if (dr.Table.Columns.IndexOf(columnName) >= 0)
                {
                    if (dr[columnName] == DBNull.Value)
                        return null;
                    return dr[columnName];
                }
            }
            return null;
        }
    }
}
